<?php
/**
 * Associated with image files. Not use to query database.
 *
 */
class ImageUtil {
    /**
    * Save uploaded file. Create directory path if it is not existed
    * Added by NgaNguyen
    * @param unknown_type $objFile: HTTP upload file object
    * @param unknown_type $strPath: The directory path used to store file (physical path)
    * @param unknown_type $strFileName: The new file name
    * @return unknown The converted new file name or empty string if failed
    */
    static function saveUploadFile($objFile, $strPath, $strFileName)
    {

        //-- remove trailling slash
        if ($strPath{strlen($strPath)-1}=='/') $strPath = substr($strPath, 0, -1);

        //-- convert filename and move the uploaded file
        $strFileName = ImageUtil::convertFileName($strFileName);
        if (@move_uploaded_file($objFile['tmp_name'], "{$strPath}/{$strFileName}")===FALSE)
            return('');
        else return ($strFileName);
    }

    /**
    * Convert name into url
    * Added by NgaNguyen
    * @param  $strName:    Input name string
    * @return $strRes :     converted string
    */
    static function convertFileName( $strName )
    {
        $CutSpaceStrName = trim($strName);
        $StrNameToLower  = strtolower($CutSpaceStrName);
        $strResConvert     = ereg_replace("[^a-z0-9_.-]", "_", $StrNameToLower);
        $strRes          = $strResConvert;
        return $strRes;
    }


    /**
    * Function:     [CreateThumbnail]
    * Description:    Create thumbnail image and then save with a prefix 'sm_' filename
    * Input:    $strPath    : the files path
    *            $imgSrc        : source image file name
    *            $maxWidth    : zero value means scale by height
    *            $maxHeight    : zero value means scale by width
    */
    static function createThumbnail($strPath, $imgSrc, $maxWidth=0, $maxHeight=0, $prefix='sm_')
    {
        //-- retrieve the image's info
        $imgInfo = @getimagesize("$strPath/$imgSrc");
        if ($imgInfo == FALSE) return(null);

        //-- determine the destinaton's image size
        $dstWidth  = $imgInfo[0];
        $dstHeight = $imgInfo[1];
        if ($maxWidth>0){
            if ($dstWidth>$maxWidth){
                $dstWidth  = $maxWidth;
                $dstHeight = $imgInfo[1] * $maxWidth / $imgInfo[0];
            }
        } else {
            if ($dstHeight>$maxHeight){
                $dstWidth  = $imgInfo[0] * $maxHeight / $imgInfo[1];
                $dstHeight = $maxHeight;
            }
        }

        //-- scale image
        switch ($imgInfo[2]){
            case 1:
                $srcImage = imagecreatefromgif("$strPath/$imgSrc");
            break;
            case 2:
                $srcImage = imagecreatefromjpeg("$strPath/$imgSrc");
            break;
            case 3:
                $srcImage = imagecreatefrompng("$strPath/$imgSrc");
            break;
            default: return(false);
        }
        $dstImage = imagecreatetruecolor($dstWidth, $dstHeight);
        imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, $dstWidth, $dstHeight, $imgInfo[0], $imgInfo[1]);

        //-- save file
        switch ($imgInfo[2]){
            case 1:
                imagegif($dstImage, "$strPath/{$prefix}{$imgSrc}");
            break;
            case 2:
                imagejpeg($dstImage, "$strPath/{$prefix}{$imgSrc}");
            break;
            case 3:
                imagepng($dstImage, "$strPath/{$prefix}{$imgSrc}");
            break;
            default: return(null);
        }
        return(array($dstWidth,$dstHeight));
    }

    /**
    * Function:     [CreateThumbnailCon]
    * Description:    Create thumbnail image and then save with a prefix 'sm_' filename
    * Input:    $strPath    : the files path
    *            $imgSrc        : source image file name
    *            $maxWidth    : zero value means scale by height
    *            $maxHeight    : zero value means scale by width
    *            $flag        : false: width and height thay doi theo, true: fix cung width and height
    * Output                : array(width, height)
    */
    static function createThumbnailCon($strPath, $imgSrc, $maxWidth=0, $maxHeight=0, $flag = false, $prefix='vnf_', $quality = 75)
    {
        //-- retrieve the image's info
        $imgInfo = @getimagesize("$strPath/$imgSrc");
        if ($imgInfo == FALSE) return(null);


        //-- determine the destinaton's image size
        $dstWidth  = $imgInfo[0];
        $dstHeight = $imgInfo[1];
        if ($maxWidth>0){
//            if ($dstWidth>$maxWidth){
                $dstWidth  = $maxWidth;
                if ( $flag )
                    $dstHeight = $maxHeight;
                else
                    $dstHeight = $imgInfo[1] * $maxWidth / $imgInfo[0];
//            }
        } else {
//            if ($dstHeight>$maxHeight){
                if ( $flag )
                    $dstWidth  = $maxWidth;
                else
                    $dstWidth  = $imgInfo[0] * $maxHeight / $imgInfo[1];
                $dstHeight = $maxHeight;
//            }
        }

        //-- create prefix
        $prefix = $prefix.$dstWidth."x".$dstHeight."_";

        //-- scale image
        switch ($imgInfo[2]){
            case 1:
                $srcImage = imagecreatefromgif("$strPath/$imgSrc");
            break;
            case 2:
                $srcImage = imagecreatefromjpeg("$strPath/$imgSrc");
            break;
            case 3:
                $srcImage = imagecreatefrompng("$strPath/$imgSrc");
            break;
            default: return(false);
        }
        $dstImage = imagecreatetruecolor($dstWidth, $dstHeight);
        imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, $dstWidth, $dstHeight, $imgInfo[0], $imgInfo[1]);

        //-- save file
        switch ($imgInfo[2]){
            case 1:
                imagegif($dstImage, "$strPath/{$prefix}{$imgSrc}");
            break;
            case 2:
                imagejpeg($dstImage, "$strPath/{$prefix}{$imgSrc}", $quality);
            break;
            case 3:
                imagepng($dstImage, "$strPath/{$prefix}{$imgSrc}", $quality);
            break;
            default: return(null);
        }
        return(array($dstWidth,$dstHeight));
    }


    /**
    * <p>Get image has condition
    * @return string
    * Input:    $strPath    : the files path
    *            $imgSrc        : source image file name
    *            $maxWidth    : zero value means scale by height
    *            $maxHeight    : zero value means scale by width
    *            $flag        : false: width and height tu dong scale, true: fix cung width and height
    * Output: $strFileName : path + sm_ + flag + "_" + width + "x" + height + "_" + imageName
    *                          Ex:
    *                            + flag = false
    *                                C:\wamp\www\img_test/sm__80x80_1231726888_251208.jpg
    *                            + flag = true
    *                                C:\wamp\www\img_test/sm_1_80x100_1231726888_251208.jpg
    */
    static function getImageCon($filePath, $fileName, $maxWidth=0, $maxHeight=0, $quality = 75, $flag = false, $prefix='vnf_', $show = true)
    {
        if(!defined('DIR_MAIN')) {
            define('DIR_MAIN', BASE_PATH);
        }
//        echo $strFileName = DIR_MAIN . $fileName;
//        echo "<hr>" . $realPath = realpath(DIR_MAIN);
//        echo "<hr>" .
        $realPath = $_SERVER['DOCUMENT_ROOT'] . DIR_MAIN . $filePath;

        $imgSrc = "$fileName";
//        echo "<hr>$realPath/$fileName-"  . is_file("$realPath/$fileName") . "<hr>";
        // check source exists
        if (is_file("$realPath/$fileName")) {
//            list($width, $height, $type, $attr) = getimagesize("$realPath/$fileName");

            if($flag == false)
            {
//                echo "hello";
                $currSize = ImageUtil::getTrueImageSize($realPath,$imgSrc,$maxWidth,$maxHeight);
                $maxWidth = $currSize[0];
                $maxHeight = $currSize[1];
            }
            $newFile = $prefix.$maxWidth."x".$maxHeight."_".$imgSrc;
            $strFileNameReturn = DIR_MAIN . "$filePath/$newFile";

            // check thumbsnail exists
            if (!file_exists($realPath ."/" . $newFile)) {
                $result = ImageUtil::createThumbnailCon($realPath, $imgSrc, $maxWidth, $maxHeight, $flag, $prefix, $quality);
//                $strFileNameReturn = $filePath . "/" . $prefix.$result[0]."x".$result[1]."_".$imgSrc;
            }
        } else {
            // return no image if file not exists
            if($show == true){
                $strFileNameReturn = DIR_MAIN . "/userfile/upload/image/noimage.jpg";
            }
            else{
                $strFileNameReturn = '';
            }
        }
//        echo $strFileNameReturn;
        return $strFileNameReturn;
    }


    /**
    * get true image size
    * Added by NgaNguyen
    * @param $strPath      : the files path
    * @param $imgSrc        : source image file name
    * @param $maxWidth        : zero value means scale by height
    * @param $maxHeight    : zero value means scale by width
    * @return array(width, height)
    */
    static function getTrueImageSize($strPath, $imgSrc, $maxWidth=0, $maxHeight=0)
    {
        //-- retrieve the image's info
        $imgInfo = @getimagesize("$strPath/$imgSrc");
        if ($imgInfo == FALSE) return(null);

        //-- determine the destinaton's image size
        $dstWidth  = $imgInfo[0];
        $dstHeight = $imgInfo[1];
        if ($maxWidth>0){
            if ($dstWidth>$maxWidth){
                $dstWidth  = $maxWidth;
                $dstHeight = $imgInfo[1] * $maxWidth / $imgInfo[0];
            }
        } else {
            if ($dstHeight>$maxHeight){
                $dstWidth  = $imgInfo[0] * $maxHeight / $imgInfo[1];
                $dstHeight = $maxHeight;
            }
        }

        return(array($dstWidth,$dstHeight));
    }

    /**
    * Create thumbnail follow width and height
    * Added by phuongpham
    * @param unknown_type $strPath: getcwd().'/'.AVATAR_UPLOAD_PATH
    * @param unknown_type $imgSrc: avatar.jpg
    * @param unknown_type $maxWidth: 100
    * @param unknown_type $maxHeight: 100
    * @param unknown_type $prefix: 100x100_
    * @return unknown
    */
    static function createThumbnailWidthAndHeight($strPath, $imgSrc, $maxWidth=0, $maxHeight=0, $prefix='sm_', $quality = 75)
    {
        //-- retrieve the image's info
        $imgInfo = @getimagesize("$strPath/$imgSrc");

        if ($imgInfo == FALSE) return(null);

        //-- determine the destinaton's image size
        $dstWidth  = $imgInfo[0];
        $dstHeight = $imgInfo[1];
        if ($maxWidth>0){
            if ($dstWidth>$maxWidth){
                $dstWidth  = $maxWidth;
                $dstHeight = $imgInfo[1] * $maxWidth / $imgInfo[0];
            }
        }
        if ($maxHeight > 0 && $dstHeight>$maxHeight){
            $dstWidth  = $imgInfo[0] * $maxHeight / $imgInfo[1];
            $dstHeight = $maxHeight;
        }


        //-- scale image
        switch ($imgInfo[2]){
            case 1:
                $srcImage = imagecreatefromgif("$strPath/$imgSrc");
            break;
            case 2:
                $srcImage = imagecreatefromjpeg("$strPath/$imgSrc");
            break;
            case 3:
                $srcImage = imagecreatefrompng("$strPath/$imgSrc");
            break;
            default: return(false);
        }
        $dstImage = imagecreatetruecolor($dstWidth, $dstHeight);
        imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, $dstWidth, $dstHeight, $imgInfo[0], $imgInfo[1]);

        //-- save file
        switch ($imgInfo[2]){
            case 1:
                imagegif($dstImage, "$strPath/{$prefix}{$imgSrc}");
            break;
            case 2:
                imagejpeg($dstImage, "$strPath/{$prefix}{$imgSrc}", $quality);
            break;
            case 3:
                imagepng($dstImage, "$strPath/{$prefix}{$imgSrc}");
            break;
            default: return(null);
        }
        return(array($dstWidth,$dstHeight));
    }

    /**
    * Crop Image
    * Added by phuongpham
    * @param unknown_type $strPath: getcwd().'/'.AVATAR_UPLOAD_PATH
    * @param unknown_type $imgSrc: avatar.jpg
    * @param unknown_type $nw: 100
    * @param unknown_type $nh: 100
    * @param unknown_type $prefix: 100x100_
    */
    static function cropImage($strPath, $imgSrc, $nw, $nh, $prefix='sm_', $quality = 75) {

        $source = $strPath.'/'.$imgSrc;
        $dest = $strPath.'/'.$prefix. $imgSrc;

        $size = @getimagesize($source);
        $w = $size[0];
        $h = $size[1];

        $stype = $size[2];
        switch($stype) {
            case 1:
            $simg = imagecreatefromgif($source);
            break;
            case 2:
            $simg = imagecreatefromjpeg($source);
            break;
            case 3:
            $simg = imagecreatefrompng($source);
            break;
        }

        $dimg = imagecreatetruecolor($nw, $nh);

        $wm = $w/$nw;
        $hm = $h/$nh;

        $h_height = $nh/2;
        $w_height = $nw/2;

        if($w> $h) {

            $adjusted_width = $w / $hm;
            $half_width = $adjusted_width / 2;
            $int_width = $half_width - $w_height;

            imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);

        } elseif(($w <$h) || ($w == $h)) {

            $adjusted_height = $h / $wm;
            $half_height = $adjusted_height / 2;
            $int_height = $half_height - $h_height;

            imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);

        } else {
            imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
        }

        imagejpeg($dimg,$dest,$quality);
    }


    /**
    * <p>Get image has condition
    * @return string
    * Input:    $strPath    : the files path
    *            $imgSrc        : source image file name
    *            $maxWidth    : zero value means scale by height
    *            $maxHeight    : zero value means scale by width
    *            $autoScale        : true: width and height tu dong scale, false: fix cung width and height
    * Output: $strFileName : path + sm_ + flag + "_" + width + "x" + height + "_" + imageName
    *                          Ex:
    *                            + flag = false
    *                                C:\wamp\www\img_test/sm__80x80_1231726888_251208.jpg
    *                            + flag = true
    *                                C:\wamp\www\img_test/sm_1_80x100_1231726888_251208.jpg
    */
    static function getImage($filePath, $fileName, $maxWidth=1024, $maxHeight=800, $quality = 75, $autoScale = true, $prefix='vnf_', $show = true)
    {
//        echo "Hello";
        if(!defined('DIR_MAIN')) {
            define('DIR_MAIN', BASE_PATH);
        }
        
        ini_set('memory_limit', '128M');
        $realPath = $_SERVER['DOCUMENT_ROOT'] . DIR_MAIN . $filePath;

//        $imgSrc = "$fileName";
//        echo "<hr>$realPath/$fileName-"  . is_file("$realPath/$fileName") . "<hr>";
        // check source exists
        if (is_file("$realPath/$fileName")) {
//            echo $realPath;
            list($width, $height, $type, $attr) = getimagesize("$realPath/$fileName");

/*            w = 10 h = 12;
            mx =5 mh = 5     =>  4.5x 5
            w = 5 h = 12;
            mx =6 mh = 5     =>  4.5x 5
            w = 5 h = 5;
            mx =6 mh = 5     =>  4.5x 5*/
            if($autoScale)
            {
//                echo "hello";
                $ratioW = $maxWidth/$width;
                if(null != $maxHeight)
                    $ratioH = $maxHeight/$height;
                else
                    $ratioH = $ratioW;

                $ratio = $ratioW<$ratioH ? $ratioW:$ratioH;

                $ratio = $ratio<1?$ratio:1;

//                $currSize = ImageUtil::getTrueImageSize($realPath,$imgSrc,$maxWidth,$maxHeight);
                $maxWidth = ceil($width*$ratio);
                $maxHeight = ceil($height*$ratio);
            }
            $newFile = $prefix.$maxWidth."x".$maxHeight."_".$fileName;
            $strFileNameReturn = DIR_MAIN . "$filePath/$newFile";

            // check thumbsnail exists
            if (!file_exists($realPath ."/" . $newFile)) {
//                $result = ImageUtil::createThumbnailCon($realPath, $fileName, $maxWidth, $maxHeight, $autoScale, $prefix, $quality);
//                $strFileNameReturn = $filePath . "/" . $prefix.$result[0]."x".$result[1]."_".$fileName;
                switch ($type){
                    case 1:
                        $srcImage = imagecreatefromgif("$realPath/$fileName");
                    break;
                    case 2:
                        $srcImage = imagecreatefromjpeg("$realPath/$fileName");
                    break;
                    case 3:
                        $srcImage = imagecreatefrompng("$realPath/$fileName");
                    break;
                    default: return(false);
                }

                $dstImage = imagecreatetruecolor($maxWidth, $maxHeight);
                imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, $maxWidth, $maxHeight, $width, $height);

                //-- save file
                switch ($type){
                    case 1:
                        imagegif($dstImage, "$realPath/$newFile");
                        break;
                    case 2:
                        imagejpeg($dstImage, "$realPath/$newFile", $quality);
                        break;
                    case 3:
                        imagepng($dstImage, "$realPath/$newFile");
                        break;
                    default: break;
                }
            }
        } else {
            // return no image if file not exists
            if($show == true){
                $strFileNameReturn = DIR_MAIN . "/userfile/upload/image/noimage.jpg";
            }
            else{
                $strFileNameReturn = '';
            }
        }
//        echo $strFileNameReturn;
        return $strFileNameReturn;
    }
    }